<template>
	<xn-form-container title="质检详情" width="90%" :visible="visible" :destroy-on-close="true" @close="onClose">
		<spin>
			<a-row :gutter="[0, 0]" class="call-autio">
				<a-col :span="20">
					<WaveSurferAudio
						v-if="curRecord.fileUrl"
						:audio-url="curRecord.fileUrl"
						@timeUpdate="handleTimeUpdate"
					></WaveSurferAudio>
					<div v-else class="empty-audio">
						<i class="iconfont icon-queshengye_zanwushuju"></i>
						<span>音频出逃了~</span>
					</div>
					<!-- <WaveSurferAudio :audio-url="curRecord.fileUrl" @timeUpdate="handleTimeUpdate"></WaveSurferAudio> -->
				</a-col>
				<a-col :span="3" class="ml-10">
					<div class="opration-btn">
						<a-button type="primary" @click="showModal('分公司质检审核')">分公司质检审核</a-button>
						<a-button v-if="isShow" type="primary" @click="showModal('总部质检审核')">总部质检审核
						</a-button>
						<a-button v-if="isShow" type="primary" @click="showModal('终审')">终审</a-button>
					</div>
					<a-modal v-model:open="open" :title="modalTitle">
						<a-form ref="formRef" :model="formData" class="mt-6">
							<a-form-item label="审核状态" name="status">
								<a-select
									v-model:value="formData.status"
									style="width: 40%"
									placeholder="请选择问题方"
									:options="voiceCheckStatusOptions"
									:disabled="checkDisabled"
								/>
							</a-form-item>
							<a-form-item label="审核备注" name="remark">
								<a-textarea
									v-model:value="formData.remark"
									placeholder="请输入审核备注"
									:auto-size="{ minRows: 4, maxRows: 8 }"
									:disabled="checkDisabled"
								/>
							</a-form-item>
						</a-form>
						<template #footer>
							<a-button @click="modalCancel">取消</a-button>
							<a-button v-if="!checkDisabled" type="primary" @click="saveApproveStatus"
									  :loading="checkSaveLoading"
							>确定
							</a-button
							>
						</template>
					</a-modal>
				</a-col>
			</a-row>
			<a-row :gutter="[10, 0]" class="call-info">
				<a-col :span="17">
					<a-card title="话单详情">
						<a-descriptions size="small" layout="horizontal" bordered class="des-details">
							<a-descriptions-item label="通话序列号">{{ curRecord.callId }}</a-descriptions-item>
							<a-descriptions-item label="被叫">{{ curRecord.liaisonPhone }}</a-descriptions-item>
							<a-descriptions-item label="通话类型">{{ curRecord.callTypeName }}</a-descriptions-item>
							<a-descriptions-item label="所属公司">{{ curRecord.deptName }}</a-descriptions-item>
							<a-descriptions-item label="坐席账号">{{ curRecord.agentName }}</a-descriptions-item>
							<a-descriptions-item label="坐席姓名">{{ curRecord.userName }}</a-descriptions-item>
						</a-descriptions>
					</a-card>
				</a-col>
				<a-col :span="7">
					<a-card title="命中关键字">
						<CiYunTu03 :callId="callId" :record="curRecord"/>
					</a-card>
				</a-col>
			</a-row>
			<a-row :gutter="[10, 0]" class="call-chat">
				<a-col :span="17">
					<a-spin :spinning="chatLoading">
						<ChatWindow
							ref="chatWindowRef"
							:current-user="currentUser"
							:target-user="targetUser"
							:messages="messages"
							:curMsgId="curMsgId"
						/>
					</a-spin>
				</a-col>
				<a-col :span="7">
					<a-card title="AI 推理过程">
						<span v-if="aiReason">{{ aiReason }}</span>
						<p v-else class="empty-remark">
							<i class="iconfont icon-queshengye_zanwushuju"></i>
							<span>爱莫能助啦~</span>
						</p>
					</a-card>
				</a-col>
			</a-row>
		</spin>
	</xn-form-container>
</template>

<script setup>
import voiceTextApi from '@/api/qc/voice/text/voiceTextApi'
import tool from '@/utils/tool'
import voiceCheckApi from '@/api/qc/voice/check/voiceCheckApi'
import CiYunTu03 from '@/views/qc/voice/check/CiYunTu03.vue'
//仿微信聊天记录
import {ref} from 'vue'
// import ChatWindow from '@/views/qc/voice/chat/ChatWindow.vue'
import ChatWindow from '@/views/qc/voice/dynamicChat/ChatWindow.vue'
import WaveSurferAudio from '@/components/AudioView/waveSurferAudio.vue'
// ===========================================DATA======================================================
const formData = ref({
	id: null,
	status: null,
	remark: null
})
const modalTitle = ref('质检审核')
const curRecord = ref({})
const checkDisabled = ref(false)
const formRef = ref()
const checkSaveLoading = ref(false)
const isShow = tool.data.get('USER_INFO').orgId === '1863060384407973889' //是否显示总部质检按钮，该ID为业务运营部，总部质检员属于业务运营部
const chatWindowRef = ref(null)
const chatLoading = ref(false)
const curMsgId = ref(null) //当前播放的消息id

// 模拟数据
const currentUser = reactive({
	id: 1,
	name: '客服',
	avatar: new URL('@/assets/images/service_avatar.png', import.meta.url).href
})

const targetUser = reactive({
	id: 2,
	name: '客户',
	avatar: new URL('@/assets/images/customer_avatar.png', import.meta.url).href
})

const messages = ref([])

const emit = defineEmits({successful: null})
const visible = ref(false)
const audioUrl = ref()
const aiReason = ref()

const isStop = ref(false)
const callRecord = ref({
	callId: undefined,
	callee: undefined,
	agentNum: undefined,
	userName: undefined,
	companyName: undefined,
	callTypeName: undefined
})

const voiceCheckStatusOptions = tool.dictList('voiceCheckStatus')
const callId = ref()
const open = ref(false)


// ===========================================METHODS======================================================

// 关闭抽屉
const onClose = () => {
	stopAudio()
	visible.value = false
	curMsgId.value = null
}

// 停止音频播放
const stopAudio = () => {
	isStop.value = true
	setTimeout(() => {
		isStop.value = false
	}, 500)
}

const showModal = (v) => {
	open.value = true
	modalTitle.value = v
	switch (v) {
		case '分公司质检审核':
			formData.value.status = curRecord.value.qualityApproveStatus
			formData.value.remark = curRecord.value.qualityApproveRemark
			break
		case '总部质检审核':
			formData.value.status = curRecord.value.supervisorApproveStatus
			formData.value.remark = curRecord.value.supervisorApproveRemark
			break
		case '终审':
			formData.value.status = curRecord.value.masterApproveStatus + ''
			formData.value.remark = curRecord.value.masterApproveRemark
			break
	}
	formData.value.id = curRecord.value.id
	checkDisabled.value = formData.value.status > 0 && formData.value.remark
}
const modalCancel = () => {
	formRef.value.resetFields()
	open.value = false
}

//录音时间更新
const handleTimeUpdate = (curTime) => {
	if (!messages.value.length) return
	// console.log('messages', messages.value)

	// 将当前时间转换为mm:ss格式用于比较
	const minutes = Math.floor(curTime / 60000)
	const seconds = Math.floor((curTime % 60000) / 1000)
	const currentTimeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
	// 找到当前时间对应的消息
	let foundMessage = null
	for (let i = 0; i < messages.value.length; i++) {
		// 比较时间字符串，找到小于等于当前播放时间的最新消息
		if (messages.value[i].timeOffset <= currentTimeString) {
			foundMessage = messages.value[i]
		} else {
			// 如果找到了大于当前时间的消息，说明前一条是我们要找的
			break
		}
	}

	// 如果找到了对应消息，设置当前消息ID
	if (foundMessage) {
		// 只有当ID变化时才更新，避免不必要的重渲染
		if (curMsgId.value !== foundMessage.id) {
			curMsgId.value = foundMessage.id
			// 滚动到当前消息
			if (chatWindowRef.value) {
				chatWindowRef.value.scrollToMessage(foundMessage.id)
			}
		}
	}
}
// ===========================================REQUEST======================================================
// 打开抽屉
const onOpen = (record) => {
	curRecord.value = record
	visible.value = true
	chatLoading.value = true
	audioUrl.value = record.fileUrl
	aiReason.value = record.aiReasonContent
	callId.value = record.callId
	// console.log(record)
	//查询语音文本
	voiceTextApi
		.getTextByCallId(record.callId)
		.then((res) => {
			chatLoading.value = false
			//原来的聊天记录
			// messageList.value = res;
			//仿微信聊天记录
			messages.value = []

			// 计算对话的起始和结束时间
			// const startTime = new Date(testData1[0].chatTime).getTime()
			// testData1.forEach((item) => {
			// 	// 计算当前消息相对于起始时间的偏移（毫秒）
			// 	const messageTime = new Date(item.chatTime).getTime()
			// 	const offsetMs = messageTime - startTime
			// 	// 转换为mm:ss格式
			// 	const minutes = Math.floor(offsetMs / 60000)
			// 	const seconds = Math.floor((offsetMs % 60000) / 1000)
			// 	const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
			// 	messages.value.push({
			// 		id: item.id,
			// 		content: item.content,
			// 		timestamp: item.chatTime,
			// 		isSelf: item.speakerRole === 2,
			// 		timeOffset: timeString
			// 	})
			// })

			const startTime = new Date(res[0].chatTime).getTime()
			res.forEach((item) => {
				// 计算当前消息相对于起始时间的偏移（毫秒）
				const messageTime = new Date(item.chatTime).getTime()
				const offsetMs = messageTime - startTime
				// 转换为mm:ss格式
				const minutes = Math.floor(offsetMs / 60000)
				const seconds = Math.floor((offsetMs % 60000) / 1000)
				const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
				messages.value.push({
					id: item.id,
					content: item.content,
					timestamp: item.chatTime,
					isSelf: item.speakerRole === 2,
					timeOffset: timeString
				})
			})
		})
		.catch((err) => {
			chatLoading.value = false
		})
	// 查询话单
	// callReceiptApi
	// 	.pageList({
	// 		current: 1,
	// 		size: 1,
	// 		beginTime: '2024-10-01 00:00:00',
	// 		endTime: `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
	// 		callId: record.callId
	// 	})
	// 	.then((res) => {
	// 		// console.log('rrrr', res)
	// 		if (res && res.records && res.records[0]) {
	// 			callRecord.value = res.records[0]
	// 		} else {
	// 			callRecord.value.userName = ''
	// 			callRecord.value.companyName = ''
	// 		}
	// 	})
}

const saveApproveStatus = () => {
	let obj = {}
	switch (modalTitle.value) {
		case '分公司质检审核':
			obj = {
				qualityApproveStatus: formData.value.status,
				qualityApproveRemark: formData.value.remark
			}
			break
		case '总部质检审核':
			obj = {
				supervisorApproveStatus: formData.value.status,
				supervisorApproveRemark: formData.value.remark
			}
			break
		case '终审':
			obj = {
				masterApproveStatus: formData.value.status,
				masterApproveRemark: formData.value.remark
			}
			break
	}
	checkSaveLoading.value = true
	obj.id = formData.value.id
	voiceCheckApi.modifyViolationStatus(obj).then((res) => {
		modalCancel()
		onClose()
		emit('successful')
		checkSaveLoading.value = false
	})
}

// 暴露方法供父组件调用
defineExpose({
	onOpen
})
</script>

<style lang="less" scoped>
.call-autio {
	height: 110px;
	border-bottom: 1px solid #e6e6e6;

	.opration-btn {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		align-items: start;

		> button {
			width: 100%;
		}
	}

	.empty-audio {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100%;

		.icon-queshengye_zanwushuju {
			font-size: 60px;
		}

		span {
			font-size: 14px;
			color: #999;
		}
	}
}

.call-info {
	height: 140px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 10px 0;

	> div:nth-child(2) {
		flex: 1;
	}

	:deep(.ant-card) {
		display: flex;
		flex-direction: column;
		height: 100%;

		.ant-card-head {
			padding: 0px 10px;
			border-bottom: 1px solid #f0f0f0 !important;
			min-height: 40px !important;

			.ant-card-head-title {
				padding: 0 !important;
			}
		}

		.ant-card-body {
			padding: 8px 10px;
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	:deep(.des-details) {
		width: 100%;

		.ant-descriptions-view {
			.ant-descriptions-item-content {
				span {
					display: inline-block;
					width: 100%;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}
			}
		}
	}
}

.call-chat {
	height: calc(100vh - 400px);

	:deep(.ant-card) {
		height: 100%;

		.ant-card-head {
			padding: 0px 10px;
			border-bottom: 1px solid #f0f0f0 !important;
			min-height: 40px !important;

			.ant-card-head-title {
				padding: 0 !important;
			}
		}

		.ant-card-body {
			padding: 8px 10px;
			height: calc(100% - 40px); // 减去标题高度，确保内容区域可以滚动
			overflow-y: auto;
			/* 自定义滚动条样式 */

			&::-webkit-scrollbar {
				width: 8px;
			}

			&::-webkit-scrollbar-track {
				background: #f0f0f0;
			}

			&::-webkit-scrollbar-thumb {
				background: #d6d6d6;
				border-radius: 4px;
			}

			&::-webkit-scrollbar-thumb:hover {
				background: #ccc;
			}

			.empty-remark {
				height: 88%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.icon-queshengye_zanwushuju {
					font-size: 60px;
				}

				span {
					font-size: 14px;
					color: #999;
					transform: translateY(-15px);
				}
			}
		}
	}
}
</style>
